/**
 * Created by WT-SUN on 2017/5/11.
 */
$(function () {
    /**
     * 选择培训计划
     */
    $("#planId").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_plan_func();
            }
        }]
    });
    $('#btn_save').on('click', function () {
        submitForm();
    });
    var TRAINFORM=CONSTANT.DictionaryTypeDefConstants.TRAINFORM;//培训形式
    queryComboData(TRAINFORM,'trainFormId');
    addPerson();
});
function queryComboData(code,queryId) {
    var pageId='#'+queryId;
    $.ajax({
        type: 'post',
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',
        data: {code: code},
        dataType: "json",
        success: function (result) {
            $(pageId).combobox({
                data: result,
                valueField: 'id',
                textField: 'text',
                editable: false,
                panelHeight: '200'

            });
        }
    });
}
function add_plan_func() {
    WindowManager.openLayer({
        type: 2,
        title: '选择培训计划',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/train/plan/listTb.shtml',
        callBack:function(data){
            getSelectedPlan(data);
        }
    });
}
var getSelectedPlan = function (data) {
    $("#planId").textbox('setValue', data[0].id).textbox('setText', data[0].name);
    $("#planTrainPlace").textbox('setText', data[0].planTrainPlace);
    $("#professionalTypeId").textbox('setText', data[0].proTypeIdName);
    if(data[0].isExternal == '0'){
        $("#hostDeptName").textbox('setText', data[0].hostDeptIdName);
        $("#isExternal0").attr("checked","checked");
        $("#isExternal1").removeAttr("checked");
    }else {
        $("#hostDeptName").textbox('setText', data[0].hostDeptName);
        $("#isExternal1").attr("checked","checked");
        $("#isExternal0").removeAttr("checked");
    }
    $("#planStartMonth").textbox('setText', data[0].planStartMonth);
    $("#trainLevelId").textbox('setText', data[0].trainLevelIdName);
    $("#planTrainPerson").textbox('setText', data[0].planTrainPerson);
    $("#trainDeptId").textbox('setText', data[0].trainDeptId);
    if (data[0].hasCertificate == '0'){
        $("#hasCertificate0").attr("checked","checked");
        $("#hasCertificate1").removeAttr("checked");
    }else {
        $("#hasCertificate1").attr("checked","checked");
        $("#hasCertificate0").removeAttr("checked");
    }
};

function addPerson() {
    var isHgData=[{id:'1',text:'是',selected:true},{id:'0',text:'否'}];
    $('#personTb').datagrid({
        fitColumns: true,
        idField: 'id',
        rownumbers: true,
        sortOrder: true,
        singleSelect: true,
        striped: true,
        fit: false,
        height: 300,
        url: ROOT_PATH + '/train/record/selectUserListByRecordId.shtml',
        queryParams: {
            sort: 'addTime',
            order: 'desc',
            recordId:$.getQueryParam('id')
        },
        columns: [[
            {
                field: 'id', title: 'id', hidden:true,width: 20
            },
            {field: 'userId', title: 'userId', hidden:true,width: 100},
            {field: 'realName', title: '姓名', width: 100},
            {
                field: 'deptName',
                title: '工作单位',
                width: 100,
                formatter: function (value, row, index) {
                    var name = '';
                    if (row.userDepartmentList && row.userDepartmentList.length > 0) {
                        for (var index in row.userDepartmentList) {
                            if (row.userDepartmentList[index].deptName != null) {
                                name += ',' + row.userDepartmentList[index].deptName;
                            }
                        }
                        return name.substring(1);
                    } else {
                        return '';
                    }
                }
            },
            {field: 'code', title: '编号', width: 100},
            {field: 'isQualified', title: '是否合格', width: 100,
                formatter: function (value, row, index){
                    return row.isQualified=='1'?'是':(row.isQualified=='0'?'否':'');
                },
                editor: {
                    type: 'combobox',
                    options: {
                        data: isHgData,
                        valueField: 'id',
                        editable:false,
                        textField: 'text',
                        required: true
                    }
                }},
            {field: 'score', title: '成绩', width: 100, editor: { type: 'numberbox', options: { min:0,precision:2 } }}
        ]],
        onClickRow:function (index, row) {
            if (editIndex_personTb != index){
                if (endEditingRtb()){
                    $('#personTb').datagrid('selectRow', index).datagrid('beginEdit', index);
                    editIndex_personTb = index;
                }else {
                    $('#personTb').datagrid('selectRow', editIndex_personTb);
                }
            }
        },
        onLoadSuccess: function () {
            var arr= $('#personTb').datagrid('getData');
            $("#realUserNum").textbox('setText',arr.total);
        }
    });
    $('#personTb_save').on('click', function () {
        if (endEditingRtb()){
        }
    });
    $('#personTb_add').on('click', function () {
        if (endEditingRtb()){
            WindowManager.openLayer({
                type: 2,
                title: '选择人员信息',
                area: ['1150px', '70%'],
                content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
                callBack:function(data){
                    var deptName='';
                    if (data[0].userDepartmentList && data[0].userDepartmentList.length > 0) {
                        for (var index in data[0].userDepartmentList) {
                            if (data[0].userDepartmentList[index].deptName != null) {
                                deptName += ',' + data[0].userDepartmentList[index].deptName;
                            }
                        }
                        deptName= deptName.substring(1);
                    } else {
                        deptName='';
                    }
                    $('#personTb').datagrid('appendRow',{
                        userId: data[0].id,
                        realName:data[0].realName,
                        deptName:deptName,
                        code:data[0].code,
                        isQualified:'1'
                    });
                    editIndex_personTb = $('#personTb').datagrid('getRows').length-1;
                    $('#personTb').datagrid('selectRow', editIndex_personTb).datagrid('beginEdit', editIndex_personTb);
                }
            });
        }
    });
    $('#personTb_remove').on('click', function () {
        if (editIndex_personTb == undefined){return}
        $('#personTb').datagrid('cancelEdit', editIndex_personTb).datagrid('deleteRow', editIndex_personTb);
        editIndex_personTb = undefined;
    });
}
var editIndex_personTb = undefined;
function endEditingRtb(){
    if (editIndex_personTb == undefined){return true}
    if ($('#personTb').datagrid('validateRow', editIndex_personTb)){
        $('#personTb').datagrid('endEdit', editIndex_personTb);
        editIndex_personTb = undefined;
        return true;
    } else {
        return false;
    }
}
function submitForm() {
    if (!$('#formReData').form('validate')) { layer.alert("请正确填写信息"); return $('#formReData').form('validate');}
    var objParams = $('#formReData').serializeJson();
    if (endEditingRtb()){
        $('#personTb').datagrid('acceptChanges');
    }
    var objArr1=$('#personTb').datagrid('getData');
    if(objArr1.total>0){
        var personTb= JSON.stringify(objArr1.rows);
        objParams.personTb=personTb;
    }
    $.ajax({
        url:ROOT_PATH + '/train/record/updateData.shtml',//提交地址
        data:objParams,
        type:"POST",
        dataType:"json",
        success: function (result) {
            if (result.success) {
                layer.msg('编辑成功', {
                    icon: 1,
                    time: 1000
                }, function () {
                    WindowManager.closeLayer({
                        returnValue: true
                    });
                });
            }
            else {
                layer.msg('编辑失败', {
                    icon: 2,
                    time: 1000
                });
            }
        }
    });
}